using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
using System.Data.Sql;

namespace LogAnalyzerIIS.Exporters
{
	partial class ExportToSQLWizard
	{
		private bool ProviderChanged_SQLClient = true;			// Fields on data provider page is changed

		/// <summary>
		/// Prepare an SQLClient data provider page
		/// </summary>
		/// <returns></returns>
		private bool PrepareSQLServ()
		{
			return true;
		}

		/// <summary>
		/// Makes connection string to connect to SQL-server data provider from data of wizard's fields
		/// </summary>
		/// <returns>Connection string</returns>
		private string GetSQLClientConnectionString()
		{
			// Don't remember auth info
			string connectionString = "Persist Security Info=False";

			// Data source (server)
			if (cbSQLClientServers.Text == "(local)")
				connectionString += ";Server=(local)";
			else
				connectionString += ";Data Source=" + cbSQLClientServers.Text;

			// Database (initial catalog)
			if (rbSQLClientDBName.Checked)
				connectionString += ";Initial catalog=" + cbSQLClientDBList.Text;
			else
				connectionString += ";AttachDbFilename=" + tbSQLClientDBName.Text;

			// Set to use user SQL-server instance (local)
			if (cbSQLClientServers.Text == ".\\SQLEXPRESS")
				connectionString += ";User Instance=True";

			// Authentication
			if (rbSQLClientWindowsAuth.Checked)	// Use windows auth
				connectionString += ";Integrated Security=True";
			else
			{
				// user password
				if (tbSQLClientUserName.Text != "")
					connectionString += ";User ID=" + tbSQLClientUserName.Text;

				if (tbSQLClientPassword.Text != "")
					connectionString += ";Password=" + tbSQLClientPassword.Text;
			}

			return connectionString;	// Return string
		}

		/// <summary>
		/// Validate fields on "SQLClient data provider" page and enable Next button if it's all Ok
		/// </summary>
		private void TrySQLClientNextButtonEnable()
		{
			if (cbSQLClientServers.Text != "" &&
					(
							(rbSQLClientDBName.Checked && cbSQLClientDBList.Text != "") ||
							(!rbSQLClientDBName.Checked && tbSQLClientDBName.Text != "")
					)
					)
				btnNext.Enabled = true;
			else
				btnNext.Enabled = false;
		}

		/// <summary>
		/// Adds some server names to the list of SQL-servers
		/// </summary>
		private void AddPredefinedSQLServerNames()
		{
			cbSQLClientServers.Items.Add(".\\SQLEXPRESS");
			cbSQLClientServers.Items.Add("(local)");
		}

		/// <summary>
		/// Event which occurs when selection of combobox with SQL-servers is changed
		/// </summary>
		private void cbSQLClientServers_TextChanged(object sender, EventArgs e)
		{
			// Set "changed" flag & try to enable Next button
			SQLParameterChanged(sender, e);

			grpSQLAuthentication.Enabled = false;
			grpSQLDatabase.Enabled = false;

			// Set enabled state of SQLClient data provider page
			if (cbSQLClientServers.Text.Length > 0)
				grpSQLAuthentication.Enabled = true;
		}

		private void btnTestConnection_Click(object sender, EventArgs e)
		{
			grpSQLDatabase.Enabled = false;

			// Prepare connection string
			//String connString =	"Data Source=" + cbSQLClientServers.Text + "; Integrated Security=True;";
			String connString = GetSQLClientConnectionString();

			// Create connection object
			using (SqlConnection SQLConn = new SqlConnection(connString))
			{
				try
				{
					// try connect to SQL-server
					SQLConn.Open();
				}
				catch (Exception ex)
				{
					// Show message if error
					MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
					return;
				}

				// Get database schema from the server
				DataTable tblDatabases = SQLConn.GetSchema("Databases");
				SQLConn.Close();	// Close connection

				// Clear list with databases
				cbSQLClientDBList.Items.Clear();

				// And add new database names
				foreach (DataRow row in tblDatabases.Rows)
					cbSQLClientDBList.Items.Add(row[0]);

				grpSQLDatabase.Enabled = true;
			}
		}

		/// <summary>
		/// Refresh list of available SQL-server
		/// </summary>
		private void btnSQLClientRefresh_Click(object sender, EventArgs e)
		{
			// Get table of the available data sources
			DataTable datatable1 = SqlDataSourceEnumerator.Instance.GetDataSources();

			cbSQLClientServers.Items.Clear();

			// Add  servers
			foreach (DataRow row in datatable1.Rows)
				cbSQLClientServers.Items.Add(row["ServerName"].ToString());

			AddPredefinedSQLServerNames();
		}

		/// <summary>
		/// Selecting an SQL Server database file with OpenDialog
		/// </summary>
		private void btnSQLClientBrowse_Click(object sender, EventArgs e)
		{
			OpenDataBaseFileDialog1.Filter = "Microsoft SQL Server Databases (*.mdf)|*.mdf|All files (*.*)|*.*";
			OpenDataBaseFileDialog1.Title = "Open database...";
			OpenDataBaseFileDialog1.DefaultExt = "mdf";

			if (OpenDataBaseFileDialog1.ShowDialog() == DialogResult.OK)
				tbSQLClientDBName.Text = OpenDataBaseFileDialog1.FileName;
		}

		/// <summary>
		/// Event which occurs when any field on SQLClient page is changed
		/// </summary>
		private void SQLParameterChanged(object sender, EventArgs e)
		{
			// Try to enable Next button
			TrySQLClientNextButtonEnable();

			// Set "changed" flag
			ProviderChanged_SQLClient = true;
		}

		/// <summary>
		/// Event which occurs when the list with names of SQL-servers is being droped down 
		/// </summary>
		private void cbSQLClientServers_DropDown(object sender, EventArgs e)
		{
			if (cbSQLClientServers.Items.Count <= 0)
				btnSQLClientRefresh_Click(sender, e);
		}

		/// <summary>
		/// Event which occurs when the checked state of "Win Auth" radiobutton on SQLClient page is changed
		/// </summary>
		private void rbSQLClientServerAuth_CheckedChanged(object sender, EventArgs e)
		{
			bool buttonChecked = (sender as RadioButton).Checked;

			tbSQLClientUserName.Enabled = buttonChecked;
			tbSQLClientPassword.Enabled = buttonChecked;
			lblSQLClientUserId.Enabled = buttonChecked;
			lblSQLClientPassword.Enabled = buttonChecked;

			ProviderChanged_SQLClient = true;
		}

		/// <summary>
		/// Event which occurs when checked state of "DBName" radiobutton on SQLClient page is changed
		/// </summary>
		private void rbSQLClientDBName_CheckedChanged(object sender, EventArgs e)
		{
			cbSQLClientDBList.Enabled = (sender as RadioButton).Checked;
			TrySQLClientNextButtonEnable();		// Try to enable Next button
			ProviderChanged_SQLClient = true;	// Set "changed" flag
		}

		/// <summary>
		/// Event which occurs when checked state of "AttachFile" radiobutton on SQLClient page is changed
		/// </summary>
		private void rbSQLClientAtachFile_CheckedChanged(object sender, EventArgs e)
		{
			bool b = (sender as RadioButton).Checked;
			tbSQLClientDBName.Enabled = b;
			btnSQLClientBrowse.Enabled = b;
			//Not needed because [rbSQLClientDBName_CheckedChanged()] is called anyway
			//ProviderChanged_SQLClient = true;
		}

		/// <summary>
		/// Event which occurs then auth parameter on SQLClient page is changed
		/// </summary>
		private void SQLClientAuthParameterChanged(object sender, EventArgs e)
		{
			ProviderChanged_SQLClient = true;
		}
	}
}